package com.bjpowernode.crm.settings.web.controller;

import com.bjpowernode.crm.commons.Constant;
import com.bjpowernode.crm.commons.utils.DateUtils;
import com.bjpowernode.crm.commons.utils.MD5Util;
import com.bjpowernode.crm.commons.utils.Result;
import com.bjpowernode.crm.settings.domain.User;
import com.bjpowernode.crm.settings.service.LoginService;
import com.mysql.jdbc.TimeUtil;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:
 * Package:com.bjpowernode.crm.settings.web.controller
 * author:郭鑫
 */
@Controller
public class UserController {

    @Resource
    private LoginService loginService;
    @Resource
    private RedisTemplate redisTemplate;

    @RequestMapping("/settings/qx/user/toLogin.do")
    public String toLogin() {
        return "settings/qx/user/login";
    }

    /**
     * 通过用户名和密码查询用户从而验证用户登录
     * @param loginAct
     * @param loginPwd
     * @return
     */
    @RequestMapping("/settings/qx/user/login.do")
    @ResponseBody
    public Object selectUserByUsernameAndPassword(String loginAct, String loginPwd, boolean jizhuwo, HttpServletRequest request, HttpServletResponse response) throws ParseException {

        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        Result result = Result.success();
        //通过用户名判断用户是否存在
        User userisExist = loginService.selectUserByUsername(loginAct);
        if(null == userisExist)
        {
            result = Result.fail("用户名或密码错误！（用户不存在）");
            return result;
        }
        //从redis总获取登录次数
        BoundValueOperations boundValueOperations = redisTemplate.boundValueOps(loginAct);
        Integer value = (Integer) boundValueOperations.get();
        if(null != value && value == 3)
        {
            result = Result.fail("输入次数已达上线，请联系后台管理人员！");
            return result;
        }

        Map<String,Object> loginMap = new HashMap<>();
        loginMap.put("loginAct",loginAct);
        //将密码进行加密
        loginMap.put("loginPwd", MD5Util.getMD5(loginPwd));
        User user = loginService.selectUserByUsernameAndPassword(loginMap);

        if(null == user)
        {
            boundValueOperations.increment(1);
            boundValueOperations.expire(DateUtils.getRemainSecondsOneDay(new Date()), TimeUnit.SECONDS);
            result = Result.fail("用户名或密码错误！！！！！");
            return result;
        }
        //判断用户是否被锁定
        String lockState = user.getLockState();
        if(!"".equals(lockState) && lockState.equals("1"))
        {
            result = Result.fail("用户账号已被锁定，请联系后台人员");
            return result;
        }
        //判断账号是否已失效
        String expireTime = user.getExpireTime();
        Date oldTime = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(expireTime);
        if(!"".equals(lockState) &&(new Date()).after(oldTime))
        {
            result = Result.fail("账号已失效，请联系后台人员！");
            return result;
        }
        //判断用户的IP是否被允许登录
        String remoteAddr = request.getRemoteAddr();
        String remoteHost = request.getRemoteHost();
        String allowIps = user.getAllowIps();
        if(!"".equals(allowIps) && !allowIps.contains(remoteAddr))
        {
            result = Result.fail("账号IP已失效，请联系后台人员！");
            return result;
        }
        //勾选“记住我" ,将账户和密码写入cookie当中
        if(jizhuwo)
        {
            Cookie cookieAct = new Cookie("loginAct",loginAct);
            cookieAct.setMaxAge(60*60*24*7);
            Cookie cookiePwd = new Cookie("loginPwd",loginPwd);
            cookiePwd.setMaxAge(60*60*24*7);
            response.addCookie(cookieAct);
            response.addCookie(cookiePwd);
        }
        request.getSession().setAttribute(Constant.SESSION,user);
        return result;
    }

    /**
     * 用户退出操作
     * @param request
     * @return
     */
    @RequestMapping("/settings/qx/user/logout.do")
    public String loginOut(HttpServletRequest request)
    {
        request.getSession().removeAttribute(Constant.SESSION);
        return "redirect:/";
    }



}
